import React, { Component } from 'react';
import PropTypes from 'prop-types';

class ButtonDropDown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      droped: false,
    };
    this.handleClick = this.handleClick.bind(this);
    this.onClickEvent = this.onClickEvent.bind(this);
  }

  handleClick(event) {
    event.nativeEvent.stopImmediatePropagation();
    this.setState({ droped: !this.state.droped });
  }

  onClickEvent(event) {
    if (this.myRef) {
      event.stopPropagation();
      this.setState({ droped: false });
    }
  }

  componentDidMount() {
    document.addEventListener('click', this.onClickEvent);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClickEvent);
  }

  render() {
    const isShow = this.state.droped ? { display: 'block' } : { display: 'none' };
    return (
      <div className="button-drop-down-wrapper" ref={(input) => { this.myRef = input; }}>
        <button onClick={this.handleClick} className="button-drop">
          <i className="icon-black__down" />
        </button>
        <div style={isShow} className="panel-show">
          {this.props.children}
        </div>
      </div>
    );
  }

  static get propTypes() {
    return {
      children: PropTypes.any
    }
  }
}


export default ButtonDropDown;
